<?php

class LoginController extends Zend_Controller_Action {
	
	
	function init() {
		$this->initView();
		$this->view->baseUrl= $this->_request->getBaseUrl();
	}
	
	function indexAction(){
		
		$this->_redirect('/');
		
	}
	
	
	function loginAction(){
		$this->view->message='';

		
		if ($this->_request->isPost()){
			$f = new Zend_Filter_StripTags();
            $username = $f->filter($this->_request->getPost('login_name'));
            $password = $f->filter($this->_request->getPost('login_password'));
            if (empty($username)) {
                $this->view->message = 'Ёжик забыл указать имя!';
            } else {
                // setup Zend_Auth adapter for a database table
                Zend_Loader::loadClass('Zend_Auth_Adapter_DbTable');
                $dbAdapter = Zend_Registry::get('dbAdapter');
                $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
                $authAdapter->setTableName('ez_users');
                $authAdapter->setIdentityColumn('name');
                $authAdapter->setCredentialColumn('password');
				$authAdapter->setCredentialTreatment('MD5(?)');
                // Set the input credential values
                // to authenticate against
                $authAdapter->setIdentity($username);
                $authAdapter->setCredential($password);

                // do the authentication
                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($authAdapter);
                if ($result->isValid()) {
                    // success: store database row to auth's storage
                    // system. (Not the password though!)
                    $data = $authAdapter->getResultRowObject(null, 'password');
                    $auth->getStorage()->write($data);
                    $this->_redirect('/');
                } else {
                    // failure: clear database row from session
                    $this->view->message = 'Ёжик, что-то напутал :(';
                }
            }
        }
            
		
			$this->render();	
	}
	
	function logoutAction(){
		Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect('/');
	}
	
}
